package com.hong.pdf2img.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class ImageToPdfUtil {
    /**
     * 支持的图片格式
     */
    public static final String[] SUPPORTED_FORMATS = {"jpg", "jpeg", "png", "gif", "bmp", "tiff"};
    public enum Layout {
        FIT_TO_PAGE,    // 适应页面，保持宽高比
        ORIGINAL_SIZE,  // 原始尺寸
        FILL_PAGE,      // 填充整个页面
        MULTI_PER_PAGE  // 一页多图
    };
    /**
     * 检查文件是否为支持的图片格式
     */
    public static boolean isSupportedImageFormat(String filePath) {
        if (filePath == null) return false;
        String extension = filePath.substring(filePath.lastIndexOf(".") + 1).toLowerCase();
        for (String format : SUPPORTED_FORMATS) {
            if (format.equals(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 支持多种布局
     * createAdvancedPdf(imagePaths, "advanced_output.pdf", Layout.FIT_TO_PAGE, PDRectangle.A4);
     * @param imagePaths
     * @param outputPdfPath
     * @param layout
     * @param pageSize
     * @throws IOException
     */
    public static void createAdvancedPdf(List<String> imagePaths, String outputPdfPath,
                                         Layout layout, PDRectangle pageSize) throws IOException {
        try (PDDocument document = new PDDocument()) {

            for (String imagePath : imagePaths) {
                File imageFile = new File(imagePath);
                if (!imageFile.exists()) {
                    System.err.println("Image not found: " + imagePath);
                    continue;
                }

                PDPage page = new PDPage(pageSize);
                document.addPage(page);

                PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, document);

                try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
                    drawImage(contentStream, pdImage, page, layout);
                }
            }

            document.save(outputPdfPath);
            System.out.println("PDF created: " + outputPdfPath);
        }
    }

    private static void drawImage(PDPageContentStream contentStream, PDImageXObject pdImage,
                                  PDPage page, Layout layout) throws IOException {
        float pageWidth = page.getMediaBox().getWidth();
        float pageHeight = page.getMediaBox().getHeight();
        float imageWidth = pdImage.getWidth();
        float imageHeight = pdImage.getHeight();

        float x, y, width, height;

        switch (layout) {
            case ORIGINAL_SIZE:
                // 原始尺寸，居中显示
                x = (pageWidth - imageWidth) / 2;
                y = (pageHeight - imageHeight) / 2;
                width = imageWidth;
                height = imageHeight;
                break;

            case FILL_PAGE:
                // 填充整个页面（可能变形）
                x = 0;
                y = 0;
                width = pageWidth;
                height = pageHeight;
                break;

            case FIT_TO_PAGE:
            default:
                // 适应页面，保持宽高比
                float scale = Math.min(pageWidth / imageWidth, pageHeight / imageHeight);
                width = imageWidth * scale;
                height = imageHeight * scale;
                x = (pageWidth - width) / 2;
                y = (pageHeight - height) / 2;
                break;
        }

        contentStream.drawImage(pdImage, x, y, width, height);
    }

    /**
     * 一页多图布局
     * createMultiImagePdf(imagePaths, "multi_image.pdf", 3, 2);
     * @param imagePaths
     * @param outputPdfPath
     * @param imagesPerRow
     * @param imagesPerColumn
     * @throws IOException
     */
    public static void createMultiImagePdf(List<String> imagePaths, String outputPdfPath,
                                           int imagesPerRow, int imagesPerColumn) throws IOException {
        try (PDDocument document = new PDDocument()) {
            int totalImages = imagePaths.size();
            int imagesPerPage = imagesPerRow * imagesPerColumn;
            for (int i = 0; i < totalImages; i += imagesPerPage) {
                PDPage page = new PDPage(PDRectangle.A4);
                document.addPage(page);

                try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
                    // 计算每个图片的尺寸和位置
                    float pageWidth = page.getMediaBox().getWidth();
                    float pageHeight = page.getMediaBox().getHeight();

                    float cellWidth = pageWidth / imagesPerRow;
                    float cellHeight = pageHeight / imagesPerColumn;

                    for (int j = 0; j < imagesPerPage && (i + j) < totalImages; j++) {
                        String imagePath = imagePaths.get(i + j);
                        PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, document);

                        // 计算当前图片的位置
                        int row = j / imagesPerRow;
                        int col = j % imagesPerRow;

                        float x = col * cellWidth;
                        float y = pageHeight - (row + 1) * cellHeight; // PDF坐标从底部开始

                        // 计算图片在单元格内的尺寸（保持宽高比）
                        float scale = Math.min(cellWidth / pdImage.getWidth(),
                                cellHeight / pdImage.getHeight());
                        float width = pdImage.getWidth() * scale;
                        float height = pdImage.getHeight() * scale;

                        // 居中显示
                        float xOffset = (cellWidth - width) / 2;
                        float yOffset = (cellHeight - height) / 2;

                        contentStream.drawImage(pdImage, x + xOffset, y + yOffset, width, height);
                    }
                }
            }
            document.save(outputPdfPath);
            System.out.println("Multi-image PDF created: " + outputPdfPath);
        }
    }

    /**
     * 从文件夹批量创建PDF
     */
    public static void createPdfFromFolder(String folderPath, String outputPdfPath) throws IOException {
        File folder = new File(folderPath);
        if (!folder.isDirectory()) {
            throw new IllegalArgumentException("提供的路径不是文件夹: " + folderPath);
        }

        File[] imageFiles = folder.listFiles((dir, name) -> isSupportedImageFormat(name));
        if (imageFiles == null || imageFiles.length == 0) {
            throw new IllegalArgumentException("文件夹中没有找到支持的图片文件");
        }

        try (PDDocument document = new PDDocument()) {
            for (File imageFile : imageFiles) {
                addImageToDocument(document, imageFile.getAbsolutePath());
            }
            document.save(outputPdfPath);
            System.out.println("从文件夹创建PDF成功: " + outputPdfPath);
            System.out.println("处理了 " + imageFiles.length + " 张图片");
        }
    }

    private static void addImageToDocument(PDDocument document, String imagePath) throws IOException {
        PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);

        PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, document);

        float pageWidth = page.getMediaBox().getWidth();
        float pageHeight = page.getMediaBox().getHeight();
        float imageWidth = pdImage.getWidth();
        float imageHeight = pdImage.getHeight();

        float scale = Math.min(pageWidth / imageWidth, pageHeight / imageHeight);
        float scaledWidth = imageWidth * scale;
        float scaledHeight = imageHeight * scale;

        float x = (pageWidth - scaledWidth) / 2;
        float y = (pageHeight - scaledHeight) / 2;

        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
            contentStream.drawImage(pdImage, x, y, scaledWidth, scaledHeight);
        }
    }
}
